#!/usr/bin/env python3
"""
企业微信机器人快速诊断脚本
"""

import os
import requests
import json
from dotenv import load_dotenv

# 加载环境变量
load_dotenv('config.env')

def check_config():
    """检查配置"""
    print("🔧 检查配置...")
    
    configs = {
        'WECHAT_TOKEN': os.getenv('WECHAT_TOKEN'),
        'WECHAT_ENCODING_AES_KEY': os.getenv('WECHAT_ENCODING_AES_KEY'),
        'WECHAT_CORP_ID': os.getenv('WECHAT_CORP_ID'),
        'DIFY_API_URL': os.getenv('DIFY_API_URL'),
        'DIFY_API_KEY': os.getenv('DIFY_API_KEY'),
        'PORT': os.getenv('PORT', '53230')
    }
    
    missing_configs = []
    for key, value in configs.items():
        if value:
            print(f"  ✅ {key}: {value[:20]}{'...' if len(str(value)) > 20 else ''}")
        else:
            print(f"  ❌ {key}: 未配置")
            missing_configs.append(key)
    
    if missing_configs:
        print(f"\n⚠️  缺少配置项: {', '.join(missing_configs)}")
        return False
    else:
        print("\n✅ 所有配置项已设置")
        return True

def check_server():
    """检查服务器状态"""
    print("\n🌐 检查服务器状态...")
    
    port = os.getenv('PORT', '53230')
    base_url = f"http://localhost:{port}"
    
    endpoints = [
        ('/', '首页'),
        ('/health', '健康检查'),
    ]
    
    for endpoint, name in endpoints:
        try:
            response = requests.get(f"{base_url}{endpoint}", timeout=5)
            if response.status_code == 200:
                print(f"  ✅ {name}: {response.status_code}")
                if endpoint == '/health':
                    data = response.json()
                    print(f"    状态: {data.get('status', 'unknown')}")
            else:
                print(f"  ❌ {name}: {response.status_code}")
        except Exception as e:
            print(f"  ❌ {name}: 连接失败 - {e}")
    
    # 测试企业微信回调接口
    try:
        response = requests.get(f"{base_url}/wechat", timeout=5)
        print(f"  ✅ 企业微信回调接口: 可访问")
    except Exception as e:
        print(f"  ❌ 企业微信回调接口: 连接失败 - {e}")

def check_logs():
    """检查日志文件"""
    print("\n📄 检查日志文件...")
    
    log_files = ['logs/app.log', 'logs/error.log']
    
    for log_file in log_files:
        if os.path.exists(log_file):
            size = os.path.getsize(log_file)
            print(f"  ✅ {log_file}: {size} 字节")
            
            # 显示最后几行日志
            try:
                with open(log_file, 'r', encoding='utf-8') as f:
                    lines = f.readlines()
                    if lines:
                        print(f"    最后一行: {lines[-1].strip()}")
            except Exception as e:
                print(f"    读取失败: {e}")
        else:
            print(f"  ❌ {log_file}: 文件不存在")

def check_docker():
    """检查Docker状态"""
    print("\n🐳 检查Docker状态...")
    
    try:
        import subprocess
        result = subprocess.run(['docker', 'ps'], capture_output=True, text=True)
        if result.returncode == 0:
            if 'wechat_robot' in result.stdout:
                print("  ✅ Docker容器正在运行")
            else:
                print("  ⚠️  Docker容器未运行")
        else:
            print("  ❌ Docker命令执行失败")
    except Exception as e:
        print(f"  ❌ Docker检查失败: {e}")

def main():
    """主诊断函数"""
    print("=" * 60)
    print("企业微信机器人诊断工具")
    print("=" * 60)
    
    # 检查配置
    config_ok = check_config()
    
    # 检查服务器
    check_server()
    
    # 检查日志
    check_logs()
    
    # 检查Docker
    check_docker()
    
    print("\n" + "=" * 60)
    print("诊断完成")
    
    if not config_ok:
        print("❌ 发现配置问题，请检查config.env文件")
    else:
        print("✅ 基本检查通过")
    
    print("\n📋 建议操作:")
    print("1. 如果配置有问题，请检查config.env文件")
    print("2. 如果服务器未启动，请运行: ./deploy.sh")
    print("3. 查看详细日志: tail -f logs/app.log")
    print("4. 运行加密测试: python test_wechat_crypto.py")

if __name__ == '__main__':
    main() 